<template>
  <div class="app-container">
    <!-- 搜索和 操作的行为区 -->
    <div class="conduct">
      <el-input v-model="listQuery.keyword" placeholder="查找账户" class="conduct-input">
        <el-button slot="append" icon="el-icon-search" @click="handleFilter" />
      </el-input>
      <el-button class="danger-btn" @click="handleUpdate(-1, 'create')">添加</el-button>
      <el-button class="primary-btn" @click="handleDelmultip">删除</el-button>
    </div>

    <!-- 表格 -->
    <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%;"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="ID" prop="id" sortable="custom" align="center">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账户名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="密码" align="center" min-width="180px">
        <template slot-scope="{row}">
          <span>{{ row.password }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="角色" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="150">
        <template slot-scope="{row, $index}">
          <el-switch v-model="row.status" active-color="#0F8CFD" inactive-color="#B0B7C9" active-text="正常"
            inactive-text="禁用" :active-value="1" :inactive-value="0"
            @change="changeStatus(row.id, row.status, $index)" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" min-width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <span class="action action-update" @click="handleUpdate(row, 'update')">编辑</span>
          |
          <span class="action action-delete" @click="handleDelete(row,$index)">删除</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />

    <el-dialog title="账户设置" :visible.sync="dialogFormVisible" width="45%" center :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px"
        style="width: 400px; margin-left:50px;">
        <el-form-item v-if="dialogStatus=='update'" label="ID">
          <el-input v-model="temp.id" :disabled="dialogStatus=='update'" />
        </el-form-item>
        <el-form-item label="账户:" prop="userName">
          <el-input v-model="temp.userName" type="text" maxlength="18" placeholder="请输入账户名" />
        </el-form-item>

        <el-tooltip v-model="reg_tooltip" content="打开了大写!" placement="right" manual>
          <el-form-item label="密码 :" prop="password">
            <el-input :key="password_type_reg" ref="password_reg" v-model="temp.password" :type="password_type_reg"
              placeholder="请设置登入密码" name="password_reg" tabindex="2" autocomplete="off" minlength="8" maxlength="16"
              clearable @keyup.native="checkCapslock(0,$event)" @blur="reg_tooltip = false">
              <span slot="append" class="show-pwd" @click="showPwd(0)">
                <svg-icon :icon-class="password_type_reg === 'password' ? 'eye' : 'eye-open'" />
              </span>
            </el-input>

          </el-form-item>
        </el-tooltip>

        <el-tooltip v-model="reg2_tooltip" content="打开了大写!" placement="right" manual>
          <el-form-item label="确认密码:" prop="password">
            <el-input :key="password_type_reg2" ref="password_reg2" v-model="temp.again_pass" :type="password_type_reg2"
              placeholder="请再次输入密码" name="password_reg2" tabindex="3" autocomplete="off" minlength="8" maxlength="16"
              clearable @keyup.native="checkCapslock(1,$event)" @blur="reg2_tooltip = false">
              <span slot="append" class="show-pwd" @click="showPwd(1)">
                <svg-icon :icon-class="password_type_reg2 === 'password' ? 'eye' : 'eye-open'" />
              </span>
            </el-input>

          </el-form-item>
        </el-tooltip>

        <el-form-item label="角色:" required>
          <el-select v-model="temp.roleId" filterable reserve-keyword placeholder="请选择角色" style="width: 100%" clearable>
            <el-option v-for="item in list_role" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态  :">
          <el-switch v-model="temp.status" active-color="#0F8CFD" inactive-color="#B0B7C9" active-text="正常"
            inactive-text="禁用" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="danger-btn" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button class="primary-btn" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <!-- 删除的提示框 -->
    <el-dialog :visible.sync="dialogPvVisible" title="提示" width="30%" center>
      <div class="del-data del-img"><img :src="require('../../assets/img/del.png')" alt=""></div>
      <div class="del-data del-notify">确定对账号进行【删除】？</div>
      <span slot="footer" class="dialog-footer">
        <el-button class="danger-btn" @click="dialogPvVisible = false">取消</el-button>
        <el-button class="primary-btn" @click="delData">确认</el-button>
      </span>
    </el-dialog>
    <!-- 状态更改的提示框 -->
    <el-dialog :visible.sync="dialogToggle" title="提示" width="30%" center>
      <div class="del-data del-img"><img :src="require('../../assets/img/remind.png')" alt=""></div>
      <div class="del-data del-notify">确定对状态进行【更改】？</div>
      <span slot="footer" class="dialog-footer">
        <el-button class="danger-btn" @click="handleCancel">取消</el-button>
        <el-button class="primary-btn" @click="toggleStatus()">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import waves from '@/directive/waves' // waves directive
  import {
    parseTime
  } from '@/utils' // 解析时间
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  import {
    delAdmin,
    addAdmin,
    editAdmin,
    listAdmin,
    toggleAdmin,
    listRole
  } from '@/api/system'
  import {
    validPass
  } from '@/utils/validate'
  import {
    logger
  } from 'runjs/lib/common'
  const calendarTypeOptions = [{
      key: 'CN',
      display_name: 'China'
    },
    {
      key: 'US',
      display_name: 'USA'
    },
    {
      key: 'JP',
      display_name: 'Japan'
    },
    {
      key: 'EU',
      display_name: 'Eurozone'
    }
  ]

  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    name: 'Account',
    components: {
      Pagination
    },
    directives: {
      waves
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      const validatePassword = (rule, value, callback) => {
        // if (!validPass(value) && (value && value.length != 64)) {
        if (!validPass(value)) {
          callback(new Error('8~16位,包含大小写字母和数字, 可以有特殊字符'))
        } else {
          callback()
        }
      }

      return {
        multipleSelection: [],
        is_multip: false, // 是否批量删除
        tableKey: 0,
        list: null,
        total: 0, // 总条数
        listLoading: true,
        listQuery: {
          page: 1, // 第几页
          limit: 10, // 每页显示的条数row
          keyword: '' // 搜索关键字
        },
        calendarTypeOptions,
        statusOptions: ['published', 'draft', 'deleted'], // 角色
        temp: {
          id: undefined,
          userName: '',
          password: '',
          again_pass: '',
          status: '',
          role: ''
        },
        old_pass: '', // 原密码
        dialogFormVisible: false,
        dialogStatus: '',
        del_id: '',
        del_index: null,
        dialogPvVisible: false, // 删除提示框
        dialogToggle: false, // 状态更改的提示框
        rules: {
          password: [{
            required: true,
            trigger: 'blur',
            validator: validatePassword
          }],
          userName: [{
            required: true,
            trigger: 'blur',
            validator: validatePassword
          }],
          again_pass: [{
            required: true,
            trigger: 'blur',
            validator: validatePassword
          }]
        },
        list_role: [], // 获取角色和角色id的 列表
        toggle_id: '', //
        toggle_status: '', // 要切换的状态值
        password_type_reg: 'password',
        password_type_reg2: 'password',
        reg_tooltip: false, // 大写 ?
        reg2_tooltip: false, // 大写 ?
        status_index: '' // 在tab列表页面,, 要切换状态值的  下标
      }
    },
    watch: {
      dialogFormVisible: {
        handler(val, oldval) {
          if (val) {
            this.getListRole() // 获得角色列表
          }
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      // 获取 table 列表
      getList() {
        this.listLoading = true
        listAdmin(this.listQuery.page, this.listQuery.limit, this.listQuery.keyword).then(res => {
          this.list = res.data.records
          this.total = parseInt(res.data.total)

          setTimeout(() => {
            this.listLoading = false
          }, 1 * 1000)
        })
      },
      // 点击了 状态值切换
      changeStatus(id, status, index) {
        this.status_index = index
        this.toggle_id = id
        this.toggle_status = status
        this.dialogToggle = true
      },
      // 确认了  状态值切换
      toggleStatus() {
        toggleAdmin(this.toggle_id, this.toggle_status).then(res => {
          this.$notify({
            title: '成功',
            message: '状态修改成功',
            type: 'success',
            duration: 4000
          })
          // this.$message({
          //   message: "状态更改成功!",
          //   type: 'success',
          //   duration: 4000,
          //   showClose: true,
          //   center: true,
          // })
          this.getList() // 重新渲染页面
          this.dialogToggle = false
        })
      },
      // 获取角色列表
      getListRole() {
        listRole(1, 49, '').then(res => {
          this.list_role = res.data.records
        })
      },
      // 监听是否打开了大写
      checkCapslock(num, e) {
        const {
          key
        } = e
        if (num == 0) { // 注册账号: 设置密码
          this.reg_tooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z') // 若开启大写则提示文字
        } else if (num == 1) { // 注册账号: 再次输入密码
          this.reg2_tooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z') // 若开启大写则提示文字
        }
      },
      // 是否显示密码
      showPwd(num) {
        if (num == 0) {
          this.password_type_reg === 'password' ? this.password_type_reg = '' : this.password_type_reg = 'password'
          this.$nextTick(() => { // 待Dom更新完毕 获取到输入框焦点
            this.$refs.password_reg.focus()
          })
        } else if (num == 1) {
          this.password_type_reg2 === 'password' ? this.password_type_reg2 = '' : this.password_type_reg2 = 'password'
          this.$nextTick(() => { // 待Dom更新完毕 获取到输入框焦点
            this.$refs.password_reg2.focus()
          })
        }
      },
      // 取消状态管理
      handleCancel() {
        this.getList() // 重新渲染页面
        this.dialogToggle = false
      },
      // 点击了 '编辑' 或添加======================================================
      handleUpdate(row, str) {
        if (str == 'create') this.resetTemp() // 清空
        if (str == 'update') {
          this.temp = Object.assign({}, row) // 克隆一个对象
          this.old_pass = this.temp.password
          this.temp.password = '' // 不回显密码
        }
        this.dialogStatus = str

        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      // 编辑: 确认更新数据
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // if(this.temp.password == this.old_pass){   // 修改了但是没改密码
            //   editAdmin(this.temp.id, '', this.temp.roleId, this.temp.status, this.temp.userName).then(() => {
            //     // const index = this.list.findIndex(v => v.id === this.temp.id) // 找到被更改的item下标
            //     // this.list.splice(index, 1, this.temp) // 通过下标更改list的数据
            //     this.getList()
            //     this.dialogFormVisible = false
            //     this.$notify({
            //       title: '成功',
            //       message: '更新成功',
            //       type: 'success',
            //       duration: 4000
            //     })
            //   })
            // }
            if (this.temp.password == this.temp.again_pass) { // 修改的内容包括: 密码
              const cryptograph = this.$sha256(this.temp.password + this.temp.userName)
              editAdmin(this.temp.id, cryptograph, this.temp.roleId, this.temp.status, this.temp.userName).then(
                () => {
                  // const index = this.list.findIndex(v => v.id === this.temp.id) // 找到被更改的item下标
                  // this.list.splice(index, 1, this.temp) // 通过下标更改list的数据
                  this.getList()
                  this.dialogFormVisible = false
                  this.$notify({
                    title: '成功',
                    message: '更新成功',
                    type: 'success',
                    duration: 4000
                  })
                })
            } else {
              this.$message({
                message: '两次密码输入不一致!',
                type: 'error',
                duration: 4000,
                showClose: true,
                center: true
              })
            }
          }
        })
      },
      // 确认添加了一个管理员
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.temp.password != this.temp.again_pass) {
              this.$message({
                message: '两次密码输入不一致!',
                type: 'error',
                duration: 4000,
                showClose: true,
                center: true
              })
            } else {
              const cryptograph = this.$sha256(this.temp.password + this.temp.userName)
              // let data2 = Object.assign({}, this.temp)   // 克隆一个对象

              addAdmin(cryptograph, this.temp.roleId, 1, this.temp.userName).then(() => {
                // this.list.unshift(this.temp)
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 4000
                })
              })
            }
          }
        })
      },
      // 清空temp
      resetTemp() {
        this.temp = {
          id: undefined,
          userName: '',
          password: '',
          again_pass: '',
          status: 1,
          role: ''
        }
      },
      // 点击了删除===============================================
      handleDelete(row, index) {
        this.is_multip = false
        this.del_id = row.id
        this.del_index = index
        this.dialogPvVisible = true
      },
      // 点击了 批量删除
      handleDelmultip() {
        if (this.multipleSelection.length == 0) {
          this.$message({
            message: '没有被选项!',
            type: 'error',
            duration: 4000,
            showClose: true,
            center: true
          })
        } else {
          this.is_multip = true
          this.dialogPvVisible = true
        }
      },
      // 确认了删除
      delData() {
        let ids = []
        if (this.is_multip) { // 批量删
          this.multipleSelection.forEach((item, i) => {
            ids.push(item.id)
          })
          // ids = this.multipleSelection
        } else {
          ids = [this.del_id]
        }
        delAdmin(ids).then(() => {
          this.dialogPvVisible = false
          // this.list.splice(this.del_index, 1)
          this.getList()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 4000
          })
        })
      },

      // 搜索
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      // 批量选择
      handleSelectionChange(val) {
        this.multipleSelection = val
      }
    }
  }
</script>

<style lang="scss" scoped>
  $theme_text: #0F8BFD;
  $backg:rgba(0, 0, 0, 0);
  $deep_text: #5E5E5E;

  .app-container {

    // background-color: #f99 !important;
    .conduct {
      position: absolute;
      right: 0;
      top: 0;
      z-index: 9;
      width: 50%;
      display: flex;
      justify-content: space-between;

      .conduct-input {
        margin-right: 10px;
        border: 0;

        input {
          background: transparent;
          border: 0;
          -webkit-appearance: none;
          border-radius: 0px;
          padding: 12px 5px 12px 15px;
          color: $deep_text;
          // height: 47px;
          caret-color: $deep_text;

          &:-webkit-autofill {
            box-shadow: 0 0 0 1000px $backg inset !important;
            -webkit-text-fill-color: $deep_text !important;
          }
        }

        .el-button {
          color: #fff;
          background-color: #0F8CFD;
        }
      }
    }

    // background-color: #f99 !important;
    .el-table {
      .action {
        cursor: pointer;

        &:hover {
          color: $theme_text;
        }
      }
    }

    .el-dialog {
      .del-data {
        text-align: center;
        margin-bottom: 16px;

        img {
          width: 110px;
          height: 110px;
        }
      }

      .del-img {}

      // min-width: 490px !important;
      // .el-input {
      //   width: 100%;
      //   background-color: blueviolet;
      // }
    }
  }
</style>
